#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Chart types and configurations for the visualization engine

This module defines all supported chart types and their configurations.
"""

from enum import Enum
from typing import Dict, List, Any, Optional
from dataclasses import dataclass


class ChartType(Enum):
    """支持的图表类型枚举"""
    LINE = "line"
    BAR = "bar" 
    PIE = "pie"
    SCATTER = "scatter"
    AREA = "area"
    TABLE = "table"
    
    @classmethod
    def get_all_types(cls) -> List[str]:
        """获取所有支持的图表类型"""
        return [chart_type.value for chart_type in cls]
    
    @classmethod
    def is_valid_type(cls, chart_type: str) -> bool:
        """检查是否为有效的图表类型"""
        return chart_type in cls.get_all_types()


@dataclass
class ChartConfig:
    """图表配置基类"""
    chart_type: str
    title: Optional[str] = None
    description: Optional[str] = None
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            "chart_type": self.chart_type,
            "title": self.title,
            "description": self.description
        }


@dataclass
class EChartsConfig(ChartConfig):
    """ECharts图表配置"""
    x_axis: Optional[Dict[str, Any]] = None
    y_axis: Optional[Dict[str, Any]] = None
    series: Optional[List[Dict[str, Any]]] = None
    legend: Optional[Dict[str, Any]] = None
    tooltip: Optional[Dict[str, Any]] = None
    
    def to_echarts_option(self) -> Dict[str, Any]:
        """转换为ECharts option格式"""
        option = {}
        
        if self.title:
            option["title"] = {"text": self.title}
        
        if self.x_axis:
            option["xAxis"] = self.x_axis
            
        if self.y_axis:
            option["yAxis"] = self.y_axis
            
        if self.series:
            option["series"] = self.series
            
        if self.legend:
            option["legend"] = self.legend
        else:
            option["legend"] = {"show": True}
            
        if self.tooltip:
            option["tooltip"] = self.tooltip
        else:
            option["tooltip"] = {"trigger": "axis"}
            
        return option


@dataclass 
class TableConfig(ChartConfig):
    """表格配置"""
    columns: Optional[List[Dict[str, str]]] = None
    data: Optional[List[Dict[str, Any]]] = None
    pagination: bool = True
    page_size: int = 10
    
    def to_table_config(self) -> Dict[str, Any]:
        """转换为表格配置格式"""
        return {
            "type": "table",
            "columns": self.columns or [],
            "data": self.data or [],
            "pagination": self.pagination,
            "pageSize": self.page_size
        }


class SupportedCharts:
    """支持的图表类型和配置"""
    
    # 图表类型映射
    CHART_TYPE_MAPPING = {
        ChartType.LINE.value: {
            "name": "折线图",
            "description": "用于显示数据随时间或类别的变化趋势",
            "use_cases": ["趋势分析", "时间序列", "连续数据变化"],
            "required_fields": ["x_field", "y_field"],
            "echarts_type": "line"
        },
        ChartType.BAR.value: {
            "name": "柱状图", 
            "description": "用于比较不同类别的数值大小",
            "use_cases": ["分类对比", "排名显示", "数量比较"],
            "required_fields": ["x_field", "y_field"],
            "echarts_type": "bar"
        },
        ChartType.PIE.value: {
            "name": "饼图",
            "description": "用于显示各部分占整体的比例关系",
            "use_cases": ["占比分析", "构成分析", "百分比显示"],
            "required_fields": ["name_field", "value_field"],
            "echarts_type": "pie"
        },
        ChartType.SCATTER.value: {
            "name": "散点图",
            "description": "用于显示两个变量之间的相关关系",
            "use_cases": ["相关性分析", "分布分析", "异常值检测"],
            "required_fields": ["x_field", "y_field"],
            "echarts_type": "scatter"
        },
        ChartType.AREA.value: {
            "name": "面积图",
            "description": "用于显示数量随时间变化的累积效果",
            "use_cases": ["累积趋势", "堆叠分析", "面积对比"],
            "required_fields": ["x_field", "y_field"],
            "echarts_type": "line"
        },
        ChartType.TABLE.value: {
            "name": "表格",
            "description": "用于显示详细的数据列表",
            "use_cases": ["数据列表", "详细信息", "排序筛选"],
            "required_fields": ["columns"],
            "echarts_type": None
        }
    }
    
    @classmethod
    def get_chart_info(cls, chart_type: str) -> Dict[str, Any]:
        """获取图表类型信息"""
        return cls.CHART_TYPE_MAPPING.get(chart_type, {})
    
    @classmethod
    def get_chart_name(cls, chart_type: str) -> str:
        """获取图表中文名称"""
        info = cls.get_chart_info(chart_type)
        return info.get("name", chart_type)
    
    @classmethod
    def get_required_fields(cls, chart_type: str) -> List[str]:
        """获取图表类型所需的字段"""
        info = cls.get_chart_info(chart_type)
        return info.get("required_fields", [])
    
    @classmethod
    def is_echarts_type(cls, chart_type: str) -> bool:
        """判断是否为ECharts图表类型"""
        info = cls.get_chart_info(chart_type)
        return info.get("echarts_type") is not None
    
    @classmethod
    def get_echarts_type(cls, chart_type: str) -> Optional[str]:
        """获取对应的ECharts图表类型"""
        info = cls.get_chart_info(chart_type)
        return info.get("echarts_type")


# 图表识别关键词映射
CHART_KEYWORDS = {
    ChartType.LINE.value: [
        "趋势", "变化", "增长", "下降", "走势", "发展", "时间", "月份", "年份", 
        "曲线", "线性", "连续", "sequence", "trend", "change", "growth"
    ],
    ChartType.BAR.value: [
        "对比", "比较", "排名", "排序", "最高", "最低", "前几", "后几",
        "柱状", "条形", "compare", "rank", "top", "bottom", "highest", "lowest"
    ],
    ChartType.PIE.value: [
        "占比", "比例", "构成", "分布", "百分比", "份额", "组成",
        "pie", "proportion", "percentage", "composition", "distribution"
    ],
    ChartType.SCATTER.value: [
        "关系", "相关", "分布", "散点", "correlation", "relationship", 
        "scatter", "distribution", "与", "和", "关联"
    ],
    ChartType.AREA.value: [
        "累积", "堆叠", "面积", "填充", "accumulate", "stack", "area", "fill"
    ],
    ChartType.TABLE.value: [
        "列表", "详细", "明细", "哪些", "有哪些", "显示", "查看", "table", 
        "list", "detail", "show", "view", "which", "what"
    ]
}


def get_chart_type_by_keywords(question: str) -> Optional[str]:
    """根据问题中的关键词推测图表类型"""
    question_lower = question.lower()
    
    # 统计每种图表类型的关键词匹配数
    scores = {}
    for chart_type, keywords in CHART_KEYWORDS.items():
        score = sum(1 for keyword in keywords if keyword in question_lower)
        if score > 0:
            scores[chart_type] = score
    
    # 返回得分最高的图表类型
    if scores:
        return max(scores.items(), key=lambda x: x[1])[0]
    
    return None


# 默认图表配置模板
DEFAULT_CHART_CONFIGS = {
    ChartType.LINE.value: {
        "smooth": True,
        "symbol": "circle",
        "symbolSize": 6,
        "lineStyle": {"width": 2}
    },
    ChartType.BAR.value: {
        "barWidth": "60%",
        "itemStyle": {
            "borderRadius": [4, 4, 0, 0]
        }
    },
    ChartType.PIE.value: {
        "radius": ["40%", "70%"],
        "center": ["50%", "50%"],
        "roseType": False,
        "label": {"show": True},
        "labelLine": {"show": True}
    },
    ChartType.SCATTER.value: {
        "symbolSize": 8,
        "itemStyle": {
            "opacity": 0.8
        }
    },
    ChartType.AREA.value: {
        "areaStyle": {"opacity": 0.6},
        "smooth": True,
        "stack": "Total"
    }
} 